<script setup lang="ts">
import { ref } from 'vue';
import { SendIcon, Loader2Icon } from 'lucide-vue-next';
import MarkdownEditor from '@/components/markdown-editor/index.vue';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

import type { UploadResult } from '@/components/file-upload/types';
import { showError, showSuccess } from '@/lib/toast';

// 定义接口类型
interface CreateQuestionRequest {
  /** 问题标题 */
  title: string;
  /** 问题内容 */
  content: string;
  /** 附件信息 - MinIO文件路径数组 */
  attachments?: string[];
  /** 提问用户ID */
  userId: string;
  /** 问题状态（可选，默认为待回答） */
  status?: string;
  /** 问题优先级（可选，默认为普通） */
  priority?: string;
}

// 表单数据
const formData = ref({
  title: '',
  content: '',
  status: 'pending',
  priority: 'normal',
  attachments: [] as string[],
});

// 提交状态
const isSubmitting = ref(false);

// 处理 markdown 内容变化
function handleContentChange(newContent: string) {
  formData.value.content = newContent;
}

// 处理文件上传成功
function handleFileUploadSuccess(result: UploadResult) {
  formData.value.attachments.push(result.url);
}

// 验证表单
function validateForm(): boolean {
  if (!formData.value.title.trim()) {
    showError('请输入问题标题');
    return false;
  }

  if (!formData.value.content.trim()) {
    showError('请输入问题内容');
    return false;
  }

  return true;
}

// 提交问题
async function submitQuestion() {
  if (!validateForm()) {
    return;
  }

  isSubmitting.value = true;

  try {
    // 构建请求数据
    const requestData: CreateQuestionRequest = {
      title: formData.value.title.trim(),
      content: formData.value.content.trim(),
      attachments: formData.value.attachments.length > 0 ? formData.value.attachments : undefined,
      userId: 'current-user-id',
      status: formData.value.status,
      priority: formData.value.priority,
    };

    // TODO: 调用后端 API
    console.log('提交问题数据:', requestData);

    // 模拟 API 调用
    await new Promise(resolve => setTimeout(resolve, 1000));

    showSuccess('问题提交成功！');

    // 重置表单
    formData.value = {
      title: '',
      content: '',
      status: 'pending',
      priority: 'normal',
      attachments: [],
    };
  } catch (error) {
    console.error('提交问题失败:', error);
    showError('提交失败，请重试');
  } finally {
    isSubmitting.value = false;
  }
}
</script>

<template>
  <div class="h-screen flex flex-col">
    <!-- 页面标题 -->
    <div class="p-4 border-b bg-white">
      <h1 class="text-2xl font-bold text-gray-900">
        提出问题
      </h1>
      <p class="text-gray-600 mt-1">
        请详细描述您的问题，我们会尽快为您解答
      </p>
    </div>

    <!-- 主要内容区域 -->
    <div class="flex-1 flex">
      <!-- 左侧：基本信息 -->
      <div class="w-80 border-r bg-white">
        <Card class="border-0 shadow-none">
          <CardHeader class="pb-4">
            <CardTitle class="text-lg">
              问题信息
            </CardTitle>
          </CardHeader>
          <CardContent class="space-y-6">
            <!-- 标题输入 -->
            <div class="space-y-2">
              <Label for="title" class="text-sm font-medium">
                问题标题 <span class="text-red-500">*</span>
              </Label>
              <Input
                id="title"
                v-model="formData.title"
                placeholder="请输入问题标题..."
                class="text-sm"
                :disabled="isSubmitting"
              />
            </div>

            <!-- 状态选择 -->
            <div class="space-y-2">
              <Label for="status" class="text-sm font-medium">
                问题状态
              </Label>
              <Select
                v-model="formData.status"
                :disabled="isSubmitting"
              >
                <SelectTrigger class="text-sm">
                  <SelectValue placeholder="选择状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="pending">
                    待回答
                  </SelectItem>
                  <SelectItem value="answered">
                    已回答
                  </SelectItem>
                  <SelectItem value="closed">
                    已关闭
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>

            <!-- 优先级选择 -->
            <div class="space-y-2">
              <Label for="priority" class="text-sm font-medium">
                优先级
              </Label>
              <Select
                v-model="formData.priority"
                :disabled="isSubmitting"
              >
                <SelectTrigger class="text-sm">
                  <SelectValue placeholder="选择优先级" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="low">
                    低
                  </SelectItem>
                  <SelectItem value="normal">
                    普通
                  </SelectItem>
                  <SelectItem value="high">
                    高
                  </SelectItem>
                  <SelectItem value="urgent">
                    紧急
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>

            <!-- 提交按钮 -->
            <div class="pt-4">
              <Button
                :disabled="isSubmitting || !formData.title.trim() || !formData.content.trim()"
                size="lg"
                class="w-full"
                @click="submitQuestion"
              >
                <Loader2Icon
                  v-if="isSubmitting"
                  class="w-4 h-4 mr-2 animate-spin"
                />
                <SendIcon
                  v-else
                  class="w-4 h-4 mr-2"
                />
                {{ isSubmitting ? '提交中...' : '提交问题' }}
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>

      <!-- 右侧：Markdown编辑器 -->
      <div class="flex-1 bg-white">
        <div class="p-6">
          <div class="mb-4">
            <h2 class="text-lg font-semibold text-gray-900">
              问题内容 <span class="text-red-500">*</span>
            </h2>
            <p class="text-sm text-gray-600 mt-1">
              请详细描述您的问题，支持Markdown格式
            </p>
          </div>

          <MarkdownEditor
            :model-value="formData.content"
            :disabled="isSubmitting"
            :show-preview="true"
            height="h-[calc(100vh-280px)]"
            placeholder="请详细描述您的问题..."
            @update:model-value="handleContentChange"
            @file-upload-success="handleFileUploadSuccess"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@reference "tailwindcss";
</style>
